/*
 * @Author: 曹捷
 * @Date: 2019-07-19 09:19:35
 * @LastEditors: 曹捷
 * @LastEditTime: 2020-09-28 10:18:50
 * @Description: page单个页面 上拉加载
 */
import { toLogin } from '@/app-modules/utils/user'
export default {
  provide() {
    return { info: this }
  },
  data() {
    return {
      searchParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 自定义查询参数
      params: {},
      // 分页list集合
      dataList: [],
      // 请求方法 url
      tableRequest: '',
      // 默认请求返回list的key
      pageItemsKey: 'data',
      loadText: {
        contentdown: '点击或上拉加载更多',
        contentrefresh: '',
        contentnomore: '我也是有底线的~~~',
      },
      iconType: '', //snow circle
      loadColor: '#007aff',
      total: '',
      pages: '',
      test: 11,
      loadStatus: 'more', //more  loading  noMore
    }
  },
  //下拉刷新
  onPullDownRefresh() {
    this.pullDownRefresh()
  },
  // 页面上拉触底事件的处理函数
  // 上拉 加载更多  判断当前页码是否是最后一页
  onReachBottom() {
    this.loadMore()
  },
  methods: {
    pullDownRefresh() {
      this.queryDataList(true).finally(() => {
        uni.stopPullDownRefresh()
      })
    },
    loadMore() {
      if (this.searchParams.pageNum >= this.pages) {
        this.loadStatus = 'noMore'
      } else {
        this.searchParams.pageNum++
        this.queryDataList()
      }
    },
    async queryDataList(init) {
      // console.log('queryDataList -> init', init)
      if (init) {
        this.searchParams.pageNum = 1
        this.dataList = []
      }
      const params = Object.assign(this.params, (this.getQueryParam && this.getQueryParam()) || this.queryParams)
      let param = this.$util.util.cloneObj(this.searchParams)
      param.param = params
      if (this.total !== '') {
        param.total = this.total
        param.pages = this.pages
      }
      this.loadStatus = 'loading'
      const data = await this.$http[this.tableRequest](param)
      if (data.code === '0000') {
        if (this.searchParams.pageNum >= data.pages) {
          this.loadStatus = 'noMore'
        } else {
          this.loadStatus = 'more'
        }
        // 自定义处理后台数据
        if (this.beforeSuccess) {
          this.beforeSuccess(data)
        }
        this.total = data.total
        if (this.searchParams.pageNum === 1) {
          this.pages = data.pages
        }

        this.dataList = this.dataList.concat(data[this.pageItemsKey] ? data[this.pageItemsKey] : [])
        // 自定义处理后台list data
        this.afterSuccess && this.afterSuccess(this.dataList)
      } else if (data.code == 'LOGIN.001') {
        this.$show(data.errorMsg)
        toLogin()
      } else {
        if (data.code !== '0002') {
          this.afterFail && this.afterFail()
          uni.showToast({
            title: data.errorMsg,
            icon: 'none',
            duration: 2000,
          })
        }
        this.loadStatus = 'more'
      }
      uni.stopPullDownRefresh()
    },
  },
}
